<?php

namespace app\index\controller;
use app\BaseController;
use think\facade\Db;


header('Content-Type:application/json; charset=utf-8');

class Login extends BaseController {


  public function login() {

    $request = request()->param();

    if (empty($request['username']) || empty($request['password'])){
      returnJson(-2, '用户名或密码错误！');
    }

    $userModel = Db::table('user_account')->where('username', $request['username'])->find();
    if (empty($userModel)) {
      returnJson(-2, '用户名或密码错误！');
    }
    if ($userModel['password'] != md5($request['password'])){
      exit(json_encode(['code'=>-2, 'msg'=>'用户名或密码错误！']));
    }else{
      $info = [
        'id'=>$userModel['id'], 
        'username'=>$userModel['username'], 
        'nickname'=>$userModel['nickname'],
        'mobile'=>$userModel['mobile'], 
      ];
      session('user', json_encode($info));
      // 不能使用exit die 会导致Session无效（TP6 BUG）
      echo(json_encode(['code'=>0, 'msg'=>'登陆成功！', 'data'=>$info]));
    }
  }



  public function register() {
    $request = request()->param();
    if (empty($request['username'])){
      returnJson(-2, '参数错误！');
    }

    $find = Db::table('user_account')->where('username', $request['username'])->find();
    if ($find) {
      returnJson(-2, '用户名存在！');
    }
    
    $data = [
      'username' => request()->param('username'),
      'nickname' => request()->param('nickname'),
      'mobile' => request()->param('mobile'),
      'password' => md5(request()->param('password')),
    ];

    $save = Db::table('user_account')->save($data);
    if ($save) {
      returnJson(0, '添加成功！');
    }
    returnJson(-2, '添加失败！');
  }

  public function login_expire() {
    $user = json_decode(session('user'), true);
    if (!$user) {
      returnJson(-2, '');
    }
    returnJson(0, '');
  }
  
  public function out_login() {
    session('user', null);
  }

}



